/*
 * @Description: Micro挂载
 * @Autor: HuiSir<www.zuifengyun.com>
 * @Date: 2022-06-06 13:51:32
 * @LastEditTime: 2022-06-06 13:56:29
 */
import Koa from 'koa'
import Micro, { useConfig, log } from 'tcp-micro-service'

export default (): Koa.Middleware => {
    // 读取配置
    const { server, registerServer } = useConfig()

    const micro = new Micro(server.name)

    return async (ctx, next) => {
        // 挂载
        ctx.micro = micro

        // 连接注册中心
        // 先判断是否已连接
        if (!micro.hasSocket(registerServer.name)) {
            await new Promise((resolve, reject) => {
                micro.client(registerServer, (err) => {
                    if (err) {
                        reject(new Error(`服务 ${registerServer.name} 连接失败：${err.message}`))
                        return
                    }
                    log.info(`已连接到 ${registerServer.name}(注册中心) 服务`)
                    resolve(null)
                })
            })
        }

        await next()
    }
}